from typing import List, Dict, Tuple, Any
from datetime import datetime

class OHLCDataManager:
    """OHLC数据管理器 - 单独处理完整K线数据"""
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(OHLCDataManager, cls).__new__(cls)
            cls._instance._init_manager()
        return cls._instance
    
    def _init_manager(self):
        """初始化管理器"""
        self.full_data: List[Dict] = []  # 完整OHLC数据
        self.data_chunks: List[List[Dict]] = []  # 分块数据
        self.chunk_size = 1000  # 每块数据大小
        self.data_info = {
            "total_count": 0,
            "time_range": "",
            "granularity": ""
        }
    
    def store_ohlc_data(self, raw_data: List[List], granularity: str, 
                         start_time: datetime, end_time: datetime):
        """存储原始OHLC数据
        
        Args:
            raw_data: API返回的原始K线数据列表
            granularity: K线粒度
            start_time: 开始时间
            end_time: 结束时间
        """
        # 转换原始数据到标准格式
        self.full_data = []
        for item in raw_data:
            self.full_data.append({
                'timestamp': int(item[0]),  # 时间戳
                'datetime': datetime.fromtimestamp(int(item[0])/1000),  # 日期时间
                'open': float(item[1]),     # 开盘价
                'high': float(item[2]),     # 最高价
                'low': float(item[3]),      # 最低价
                'close': float(item[4]),    # 收盘价
                'volume': float(item[5]) if len(item) > 5 else 0  # 成交量
            })
        
        # 按时间排序
        self.full_data.sort(key=lambda x: x['timestamp'])
        
        # 更新数据信息
        self.data_info.update({
            "total_count": len(self.full_data),
            "time_range": f"{start_time.strftime('%Y-%m-%d %H:%M')} 至 "
                         f"{end_time.strftime('%Y-%m-%d %H:%M')}",
            "granularity": granularity
        })
        
        # 分块存储
        self._chunk_data()
        
        return len(self.full_data)
    
    def _chunk_data(self):
        """将数据分块存储"""
        self.data_chunks = []
        for i in range(0, len(self.full_data), self.chunk_size):
            self.data_chunks.append(self.full_data[i:i+self.chunk_size])
    
    def get_chunk(self, index: int) -> List[Dict]:
        """获取指定索引的数据块"""
        if 0 <= index < len(self.data_chunks):
            return self.data_chunks[index]
        return []
    
    def get_chunk_count(self) -> int:
        """获取数据块数量"""
        return len(self.data_chunks)
    
    def get_data_in_range(self, start_index: int, end_index: int) -> List[Dict]:
        """获取指定范围的数据"""
        if start_index < 0:
            start_index = 0
        if end_index >= len(self.full_data):
            end_index = len(self.full_data) - 1
            
        return self.full_data[start_index:end_index+1]
    
    def get_visible_data(self, start_time: datetime, end_time: datetime) -> List[Dict]:
        """获取指定时间范围内的数据"""
        # 转换为毫秒时间戳
        start_ts = int(start_time.timestamp() * 1000)
        end_ts = int(end_time.timestamp() * 1000)
        
        return [item for item in self.full_data 
                if start_ts <= item['timestamp'] <= end_ts]
    
    def get_latest_chunk(self) -> List[Dict]:
        """获取最新的数据块"""
        if self.data_chunks:
            return self.data_chunks[-1]
        return []
    
    def get_data_info(self) -> dict:
        """获取数据信息"""
        return self.data_info
    
    def get_all_data(self) -> List[Dict]:
        """获取全部OHLC数据"""
        return self.full_data
    
    def clear(self):
        """清空数据"""
        self.full_data = []
        self.data_chunks = []
        self.data_info = {
            "total_count": 0,
            "time_range": "",
            "granularity": ""
        }

# 全局单例实例
ohlc_data_manager = OHLCDataManager() 